package gucheng;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Classname Solution
 * @Description TODO
 * @Date 2021/12/31 15:53
 * @Created by ASUS
 */
public class Solution {
    public int removeCoveredIntervals1(int[][] intervals) {
        if (intervals.length <= 1) return intervals.length;
        Arrays.sort(intervals, (a, b) -> (a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]));
        int cur = 0, cnt = 0;
        for (int[] next : intervals) {
            if (cur < next[0]) {
                cur = next[1];
                cnt++;
            }
        }
        return cnt;
    }
    public int removeCoveredIntervals(int[][] intervals) {
        if (intervals.length <= 1) return intervals.length;
        Arrays.sort(intervals, (a, b) -> (a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]));//一定是左边的被cover
        int[] cur = intervals[0];
        List<int[]> t = new ArrayList<>();
        for (int i = 0; i < intervals.length; i++) {
            if (covered(cur, intervals[i])) {
                cur = new int[]{Math.min(cur[0], intervals[i][0]),
                        Math.max(cur[1], intervals[i][1])};
                if (i == intervals.length - 1) t.add(cur);
            } else {
                t.add(cur);
                if (i == intervals.length - 1) t.add(intervals[i]);
                cur = intervals[i];
            }
        }
        t.forEach(a -> System.out.println(Arrays.toString(a)));
        return t.size();
    }

    private boolean covered(int[] a, int[] b) {
        return a[0] <= b[0] && b[1] <= a[1] ||
                b[0] <= a[0] && a[1] <= b[1];
    }

    public static void main(String[] args) {
        System.out.println(new Solution().removeCoveredIntervals(new int[][]{{1, 4}, {3, 6}, {2, 8}}));
    }
}
